package com.cola.utils;

import com.cola.bean.Clothes;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Grup:com.cola.utils
 * @Auther:cola
 * @Data:2021/4/17-2021-04-10:29
 * @version:1.0
 */
public class ProductsXmlUtils {
    public static List<Clothes> parserProductFormXml(){
        List<Clothes> products=new ArrayList<>();
        XStream xStream = new XStream(new Xpp3Driver());
        xStream.alias("list",products.getClass());
        xStream.alias("clothes",Clothes.class);
        xStream.useAttributeFor(Clothes.class,"id");
        try {
            BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream("E:\\IdeaProjects\\MyJavaStudy\\ClothesSupermarketSystem19\\src\\main\\resources\\products.xml"));
            products=(List<Clothes>)xStream.fromXML(inputStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return products;
    }

    public static void writeproductToXml(List<Clothes> products){
        XStream xStream = new XStream(new Xpp3Driver());
        xStream.alias("list",products.getClass());
        xStream.alias("clothes",Clothes.class);
        xStream.useAttributeFor(Clothes.class,"id");
        try {
            BufferedOutputStream outputStream=new BufferedOutputStream(new FileOutputStream("E:\\IdeaProjects\\MyJavaStudy\\ClothesSupermarketSystem19\\src\\main\\resources\\products.xml"));
            outputStream.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes());
            xStream.toXML(products,outputStream);
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
